/***
* The script computes surface water extent with the CAWI index using a Canny Edge detector and Otsu thresholding
* See the following paper for details: http://www.mdpi.com/2072-4292/8/5/386
* 
* Author: Gennadii Donchyts (gennadiy.donchyts@gmail.com)
* Contributors: Nicholas Clinton (nclinton@google.com)
* Modification: Ricardo Aravena (mapmandu@gmail.com)
*/ 

Map.setOptions("SATELLITE")

// Define the bounds for the AOI:
var xMin = 152.4030529754883;
var yMin = -31.717251187998457;
var xMax = 152.62689941103517;
var yMax = -31.946516725142562;
// Construct a rectangle from a list of bounding coordinates
var AOI = ee.Geometry.Rectangle([xMin, yMin, xMax, yMax]);
Map.centerObject(AOI, 11);

/**
 * Function to mask clouds based on the pixel_qa band of Landsat 8 SR data.
 * @param {ee.Image} image input Landsat 8 SR image
 * @return {ee.Image} cloudmasked Landsat 8 image
 */
function maskL8sr(image) {
  // Bits 3 and 5 are cloud shadow and cloud, respectively.
  var cloudShadowBitMask = (1 << 3);
  var cloudsBitMask = (1 << 5);
  // Get the pixel QA band.
  var qa = image.select('pixel_qa');
  // Both flags should be set to zero, indicating clear conditions.
  var mask = qa.bitwiseAnd(cloudShadowBitMask).eq(0)
                 .and(qa.bitwiseAnd(cloudsBitMask).eq(0));
  // return image.updateMask(mask);
  return image.updateMask(mask).divide(10000);
}

// Median-based composite definition:
var Collection = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR')
                  // Pre-filter to get less cloudy granules.
                  // .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20))
                  .filter(ee.Filter.calendarRange(2016, 2018,'year')) // for Annual
                  // .filter(ee.Filter.calendarRange(9,2,'month')) // Spring to Summer (least hillshadedin the Southern Hemisphere)
                  // ... would need to be the opposite for the Northern Hemisphere
                  // .filter(ee.Filter.calendarRange(12, 2,'month')) // Summer 
                  // .filter(ee.Filter.calendarRange(3, 5,'month')) // Autumn
                  // .filter(ee.Filter.calendarRange(6, 8,'month')) // Winter
                  .filter(ee.Filter.calendarRange(9, 11,'month')) // Spring
                  .map(maskL8sr);
                  
// Get the median over time, in each band, in each pixel.
var image = Collection.median();
Map.addLayer(image, {bands: ['B5', 'B6', 'B4'], min:0, max:0.4}, 'image')

// Otsu thesholding:
var otsu = function(histogram) {
    histogram = ee.Dictionary(histogram);
    var counts = ee.Array(histogram.get('histogram'));
    var means = ee.Array(histogram.get('bucketMeans'));
    var size = means.length().get([0]);
    var total = counts.reduce(ee.Reducer.sum(), [0]).get([0]);
    var sum = means.multiply(counts).reduce(ee.Reducer.sum(), [0]).get([0]);
    var mean = sum.divide(total);
    var indices = ee.List.sequence(1, size);
    // Compute between sum of squares, where each mean partitions the data.
    var bss = indices.map(function(i) {
        var aCounts = counts.slice(0, 0, i);
        var aCount = aCounts.reduce(ee.Reducer.sum(), [0]).get([0]);
        var aMeans = means.slice(0, 0, i);
        var aMean = aMeans.multiply(aCounts)
            .reduce(ee.Reducer.sum(), [0]).get([0])
            .divide(aCount);
        var bCount = total.subtract(aCount);
        var bMean = sum.subtract(aCount.multiply(aMean)).divide(bCount);
        return aCount.multiply(aMean.subtract(mean).pow(2)).add(
            bCount.multiply(bMean.subtract(mean).pow(2)));
    });
    // Return the mean value corresponding to the maximum BSS.
    return means.sort(bss).get([-1]);
};

/***
* Compute a threshold using Otsu method (bimodal)
*/
function computeThresholdUsingOtsu(image, scale, AOI, cannyThreshold, cannySigma, minValue, debug) {
    // clip image edges
    var mask = image.mask().gt(0).focal_min(ee.Number(scale).multiply(3), 'circle', 'meters');
    // detect sharp changes
    var edge = ee.Algorithms.CannyEdgeDetector(image, cannyThreshold, cannySigma);
    edge = edge.multiply(mask);
    // buffer around CAWI edges
    var edgeBuffer = edge.focal_max(ee.Number(scale).multiply(1), 'square', 'meters');
    var imageEdge = image.mask(edgeBuffer);
    // compute threshold using Otsu thresholding
    var buckets = 100;
    var hist = ee.Dictionary(ee.Dictionary(imageEdge.reduceRegion(ee.Reducer.histogram(buckets), AOI, scale)).values().get(0));
    var threshold = ee.Algorithms.If(hist.contains('bucketMeans'), otsu(hist), 0.3);
    threshold = ee.Number(threshold)//.add(0.05)
    if(debug) {
        // Map.addLayer(edge.mask(edge), {palette:['ff0000']}, 'edges', false);
        print('Threshold: ', threshold);
        print(ui.Chart.image.histogram(image, AOI, scale, buckets));
        // print(ui.Chart.image.histogram(imageEdge, AOI, scale, buckets));
        // Map.addLayer(mask.mask(mask), {palette:['000000']}, 'image mask', false);
    }
    return minValue !== 'undefined' ? threshold.max(minValue) : threshold;
}

// CAWI 
var CAWI = image.expression(
      // 'Green/SWIR2/NIR', {
      'log10(Green/SWIR2/NIR)', {
      'Green': image.select('B3'),
      'NIR': image.select('B5'),
      'SWIR2': image.select('B7')
}).rename(['CAWI']);

var debug = true
var scale = 10
var cannyThreshold = 0.9
var cannySigma = 1
var minValue = -0.1
var th = computeThresholdUsingOtsu(CAWI, scale, AOI, cannyThreshold, cannySigma, minValue, debug)

// print(th)

function getEdge(mask) {
  return mask.subtract(mask.focal_min(1))
}

var CAWI_class = CAWI.gt(th).selfMask();
Map.addLayer(CAWI_class, {palette:'cyan'}, 'CAWI (th=' + th.getInfo() + ')');

// Slope mask:
var DEM = ee.Image('USGS/SRTMGL1_003');
var elevation = DEM.select('elevation');
var slope = ee.Terrain.slope(elevation);
var slope_mask = slope.gte(10).selfMask();
Map.addLayer(slope_mask, {min:  0, max: 1, palette: ['red', 'red']}, 'Slope mask'); 

var CAWI_w_slope_mask = CAWI_class.eq(1).updateMask(slope_mask.unmask().not());
Map.addLayer(CAWI_w_slope_mask, {palette:'cyan'}, 'CAWI with slope mask (th=' + th.getInfo() + ')');

// Display AOI:
var AOI_fc = ee.FeatureCollection(AOI);
var empty = ee.Image().byte();
var outline = empty.paint({featureCollection: AOI_fc, color: 1, width: 3});
Map.addLayer(outline, {palette: 'yellow'}, 'AOI');